/*
 * This file is part of JSTUN. 
 * 
 * Copyright (c) 2005 Thomas King <king@t-king.de> - All rights
 * reserved.
 * 
 * This software is licensed under either the GNU Public License (GPL),
 * or the Apache 2.0 license. Copies of both license agreements are
 * included in this distribution.
 */

package com.jstun.demo;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.logging.Logger;

import com.jstun.core.attribute.ChangeRequest;
import com.jstun.core.attribute.ChangedAddress;
import com.jstun.core.attribute.ErrorCode;
import com.jstun.core.attribute.MappedAddress;
import com.jstun.core.attribute.MessageAttribute;
import com.jstun.core.attribute.MessageAttributeException;
import com.jstun.core.attribute.MessageAttributeParsingException;
import com.jstun.core.header.MessageHeader;
import com.jstun.core.header.MessageHeaderParsingException;
import com.jstun.core.util.UtilityException;

public class DiscoveryTest {
	private static final Logger LOGGER = Logger.getLogger(DiscoveryTest.class.getName());
	InetAddress iaddress;
	String stunServer;
	int port;
	int timeoutInitValue = 300; //ms
	MappedAddress ma = null;
	ChangedAddress ca = null;
	boolean nodeNatted = true;
	DatagramSocket socketTest1 = null;
	DiscoveryInfo di = null;

	private boolean interrupted = false;

	private boolean running = false;

	private Object interruptSemaphore = new Object();

	public DiscoveryTest(InetAddress iaddress , String stunServer, int port, DatagramSocket socket) {
		this.iaddress = iaddress;
		this.stunServer = stunServer;
		this.port = port;
		socketTest1 = socket;
	}

	public DiscoveryInfo test() throws UtilityException, SocketException, UnknownHostException, IOException, MessageAttributeParsingException, MessageAttributeException, MessageHeaderParsingException, InterruptedException{
		try{

			synchronized (interruptSemaphore) {

				if(!interrupted){

					running = true;

				}else{
					running = false;
					interrupted = false;
					try {
						if(socketTest1.isConnected()){
							socketTest1.disconnect();
						}
					} catch (Throwable e1) {

					}
					interruptSemaphore.notify();
					throw new InterruptedException();
				}

			}

			ma = null;
			ca = null;
			nodeNatted = true;
			di = new DiscoveryInfo(iaddress);

			if (test1()) {
				if (test2()) {
					if (test1Redo()) {
						test3();
					}
				}
			}

			return di;
		}catch(InterruptedException e){
			synchronized (interruptSemaphore) {
				interrupted = false;
				running = false;
				try {
					if(socketTest1.isConnected()){
						socketTest1.disconnect();
					}
				} catch (Throwable e1) {

				}

				interruptSemaphore.notify();
			}
			throw e;

		} catch(Exception e){
			e.printStackTrace();
			return null;
		}finally{
			running = false;
			if(socketTest1.isConnected()){
				socketTest1.disconnect();
			}

		}
	}

	public DiscoveryInfo getPublicAddress() throws SocketException, UnknownHostException, MessageAttributeParsingException, MessageHeaderParsingException, UtilityException, IOException, InterruptedException{
		try{

			synchronized (interruptSemaphore) {

				if(!interrupted){

					running = true;

				}else{
					running = false;
					interrupted = false;
					try {
						if(socketTest1.isConnected()){
							socketTest1.disconnect();
						}
					} catch (Throwable e1) {

					}
					interruptSemaphore.notify();
					throw new InterruptedException();
				}

			}

			ma = null;
			ca = null;

			if(!test1()){
				throw new IOException();
			}

			return di;
		} catch (InterruptedException e) {
			synchronized (interruptSemaphore) {
				running = false;
				interrupted = false;
				try {
					if(socketTest1.isConnected()){
						socketTest1.disconnect();
					}
				} catch (Throwable e1) {

				}
				interruptSemaphore.notify();
			}
			throw e;
		}finally{

			running = false;
			if(socketTest1.isConnected()){
				socketTest1.disconnect();
			}

		}
	}

	private boolean test1() throws UtilityException, SocketException, UnknownHostException, IOException, MessageAttributeParsingException, MessageHeaderParsingException, InterruptedException {
		int timeSinceFirstTransmission = 0;
		int timeout = timeoutInitValue;

		while (true) {
			if(interrupted){
				throw new InterruptedException();
			}
			try {
				di.setTestPort(socketTest1.getLocalPort());
				// Test 1 including response
				//				socketTest1.setReuseAddress(true);
				socketTest1.connect(InetAddress.getByName(stunServer), port);
				socketTest1.setSoTimeout(timeout);

				MessageHeader sendMH = new MessageHeader(MessageHeader.MessageHeaderType.BindingRequest);
				sendMH.generateTransactionID();

				ChangeRequest changeRequest = new ChangeRequest();
				sendMH.addMessageAttribute(changeRequest);

				byte[] data = sendMH.getBytes();
				DatagramPacket send = new DatagramPacket(data, data.length);
				socketTest1.send(send);
				LOGGER.finer("Test 1: Binding Request sent.");

				MessageHeader receiveMH = new MessageHeader();
				while (!(receiveMH.equalTransactionID(sendMH))) {
					DatagramPacket receive = new DatagramPacket(new byte[200], 200);
					socketTest1.receive(receive);
					receiveMH = MessageHeader.parseHeader(receive.getData());
					receiveMH.parseAttributes(receive.getData());
				}

				ma = (MappedAddress) receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.MappedAddress);
				ca = (ChangedAddress) receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.ChangedAddress);
				ErrorCode ec = (ErrorCode) receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.ErrorCode);
				if (ec != null) {
					di.setError(ec.getResponseCode(), ec.getReason());
					LOGGER.finer("Message header contains an Errorcode message attribute.");
					return false;
				}
				if ((ma == null) || (ca == null)) {
					di.setError(700, "The server is sending an incomplete response (Mapped Address and Changed Address message attributes are missing). The client should not retry.");
					LOGGER.finer("Response does not contain a Mapped Address or Changed Address message attribute.");
					return false;
				} else {
					di.setPublicIP(ma.getAddress().getInetAddress());
					if ((ma.getPort() == socketTest1.getLocalPort()) && (ma.getAddress().getInetAddress().equals(socketTest1.getLocalAddress()))) {
						LOGGER.finer("Node is not natted.");
						nodeNatted = false;
					} else {
						LOGGER.finer("Node is natted.");
					}
					di.setPublicPort(ma.getPort());
					return true;
				}
			} catch (SocketTimeoutException ste) {
				if (timeSinceFirstTransmission < 7900) {
					LOGGER.finer("Test 1: Socket timeout while receiving the response.");
					timeSinceFirstTransmission += timeout;
					int timeoutAddValue = (timeSinceFirstTransmission * 2);
					if (timeoutAddValue > 1600) timeoutAddValue = 1600;
					timeout = timeoutAddValue;
				} else {
					// node is not capable of udp communication
					LOGGER.finer("Test 1: Socket timeout while receiving the response. Maximum retry limit exceed. Give up.");
					di.setBlockedUDP();
					LOGGER.finer("Node is not capable of UDP communication.");
					return false;
				}
			} 
		}
	}

	@SuppressWarnings("resource")
	private boolean test2() throws UtilityException, SocketException, UnknownHostException, IOException, MessageAttributeParsingException, MessageAttributeException, MessageHeaderParsingException, InterruptedException {
		int timeSinceFirstTransmission = 0;
		int timeout = timeoutInitValue;
		DatagramSocket sendSocket = new DatagramSocket(new InetSocketAddress(iaddress, 0));

		try{
			while (true) {
				if(interrupted){
					throw new InterruptedException();
				}
				try {

					// Test 2 including response
					sendSocket.connect(InetAddress.getByName(stunServer), port);
					sendSocket.setSoTimeout(timeout);

					MessageHeader sendMH = new MessageHeader(MessageHeader.MessageHeaderType.BindingRequest);
					sendMH.generateTransactionID();

					ChangeRequest changeRequest = new ChangeRequest();
					changeRequest.setChangeIP();
					changeRequest.setChangePort();
					sendMH.addMessageAttribute(changeRequest);

					byte[] data = sendMH.getBytes(); 
					DatagramPacket send = new DatagramPacket(data, data.length);
					sendSocket.send(send);
					LOGGER.finer("Test 2: Binding Request sent.");

					sendSocket.connect(ca.getAddress().getInetAddress(), ca.getPort());
					sendSocket.setSoTimeout(timeout);

					MessageHeader receiveMH = new MessageHeader();
					while(!(receiveMH.equalTransactionID(sendMH))) {
						DatagramPacket receive = new DatagramPacket(new byte[200], 200);
						sendSocket.receive(receive);
						receiveMH = MessageHeader.parseHeader(receive.getData());
						receiveMH.parseAttributes(receive.getData());
					}
					ErrorCode ec = (ErrorCode) receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.ErrorCode);
					if (ec != null) {
						di.setError(ec.getResponseCode(), ec.getReason());
						LOGGER.finer("Message header contains an Errorcode message attribute.");
						return false;
					}
					if (!nodeNatted) {
						di.setOpenAccess();
						LOGGER.finer("Node has open access to the Internet (or, at least the node is behind a full-cone NAT without translation).");
					} else {
						di.setFullCone();
						LOGGER.finer("Node is behind a full-cone NAT.");
					}
					return false;
				} catch (SocketTimeoutException ste) {
					if (timeSinceFirstTransmission < 7900) {
						LOGGER.finer("Test 2: Socket timeout while receiving the response.");
						timeSinceFirstTransmission += timeout;
						int timeoutAddValue = (timeSinceFirstTransmission * 2);
						if (timeoutAddValue > 1600) timeoutAddValue = 1600;
						timeout = timeoutAddValue;
					} else {
						LOGGER.finer("Test 2: Socket timeout while receiving the response. Maximum retry limit exceed. Give up.");
						if (!nodeNatted) {
							di.setSymmetricUDPFirewall();
							LOGGER.finer("Node is behind a symmetric UDP firewall.");
							return false;
						} else {
							// not is natted
							// redo test 1 with address and port as offered in the changed-address message attribute
							return true;
						}
					}
				}
			}
		}finally{
			if(sendSocket != null && !sendSocket.isClosed()){
				sendSocket.close();
			}
		}
	}

	private boolean test1Redo() throws UtilityException, SocketException, UnknownHostException, IOException, MessageAttributeParsingException, MessageHeaderParsingException, InterruptedException{
		int timeSinceFirstTransmission = 0;
		int timeout = timeoutInitValue;
		while (true) {
			if(interrupted){
				throw new InterruptedException();
			}
			// redo test 1 with address and port as offered in the changed-address message attribute
			try {
				// Test 1 with changed port and address values
				socketTest1.connect(ca.getAddress().getInetAddress(), ca.getPort());
				socketTest1.setSoTimeout(timeout);

				MessageHeader sendMH = new MessageHeader(MessageHeader.MessageHeaderType.BindingRequest);
				sendMH.generateTransactionID();

				ChangeRequest changeRequest = new ChangeRequest();
				sendMH.addMessageAttribute(changeRequest);

				byte[] data = sendMH.getBytes();
				DatagramPacket send = new DatagramPacket(data, data.length);
				socketTest1.send(send);
				LOGGER.finer("Test 1 redo with changed address: Binding Request sent.");

				MessageHeader receiveMH = new MessageHeader();
				while (!(receiveMH.equalTransactionID(sendMH))) {
					DatagramPacket receive = new DatagramPacket(new byte[200], 200);
					socketTest1.receive(receive);
					receiveMH = MessageHeader.parseHeader(receive.getData());
					receiveMH.parseAttributes(receive.getData());
				}
				MappedAddress ma2 = (MappedAddress) receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.MappedAddress);
				ErrorCode ec = (ErrorCode) receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.ErrorCode);
				if (ec != null) {
					di.setError(ec.getResponseCode(), ec.getReason());
					LOGGER.finer("Message header contains an Errorcode message attribute.");
					return false;
				}
				if (ma2 == null) {
					di.setError(700, "The server is sending an incomplete response (Mapped Address message attribute is missing). The client should not retry.");
					LOGGER.finer("Response does not contain a Mapped Address message attribute.");
					return false;
				} else {
					if ((ma.getPort() != ma2.getPort()) || (!(ma.getAddress().getInetAddress().equals(ma2.getAddress().getInetAddress())))) {
						di.setSymmetric();
						LOGGER.finer("Node is behind a symmetric NAT.");
						return false;
					}
				}
				return true;
			} catch (SocketTimeoutException ste2) {
				if (timeSinceFirstTransmission < 7900) {
					LOGGER.finer("Test 1 redo with changed address: Socket timeout while receiving the response.");
					timeSinceFirstTransmission += timeout;
					int timeoutAddValue = (timeSinceFirstTransmission * 2);
					if (timeoutAddValue > 1600) timeoutAddValue = 1600;
					timeout = timeoutAddValue;
				} else {
					LOGGER.finer("Test 1 redo with changed address: Socket timeout while receiving the response.  Maximum retry limit exceed. Give up.");
					return false;
				}
			}
		}
	}

	@SuppressWarnings("resource")
	private void test3() throws UtilityException, SocketException, UnknownHostException, IOException, MessageAttributeParsingException, MessageAttributeException, MessageHeaderParsingException, InterruptedException {
		int timeSinceFirstTransmission = 0;
		int timeout = timeoutInitValue;

		DatagramSocket sendSocket = new DatagramSocket(new InetSocketAddress(iaddress, 0));

		try{
			while (true) {
				if(interrupted){
					throw new InterruptedException();
				}
				try {
					// Test 3 including response
					sendSocket.connect(InetAddress.getByName(stunServer), port);
					sendSocket.setSoTimeout(timeout);

					MessageHeader sendMH = new MessageHeader(MessageHeader.MessageHeaderType.BindingRequest);
					sendMH.generateTransactionID();

					ChangeRequest changeRequest = new ChangeRequest();
					changeRequest.setChangePort();
					sendMH.addMessageAttribute(changeRequest);

					byte[] data = sendMH.getBytes();
					DatagramPacket send = new DatagramPacket(data, data.length);
					sendSocket.send(send);
					LOGGER.finer("Test 3: Binding Request sent.");

					sendSocket.connect(InetAddress.getByName(stunServer), ca.getPort());
					sendSocket.setSoTimeout(timeout);

					MessageHeader receiveMH = new MessageHeader();
					while (!(receiveMH.equalTransactionID(sendMH))) {
						DatagramPacket receive = new DatagramPacket(new byte[200], 200);
						sendSocket.receive(receive);
						receiveMH = MessageHeader.parseHeader(receive.getData());
						receiveMH.parseAttributes(receive.getData());
					}
					ErrorCode ec = (ErrorCode) receiveMH.getMessageAttribute(MessageAttribute.MessageAttributeType.ErrorCode);
					if (ec != null) {
						di.setError(ec.getResponseCode(), ec.getReason());
						LOGGER.finer("Message header contains an Errorcode message attribute.");
						return;
					}
					if (nodeNatted) {
						di.setRestrictedCone();
						LOGGER.finer("Node is behind a restricted NAT.");
						return;
					}
				} catch (SocketTimeoutException ste) {
					if (timeSinceFirstTransmission < 7900) {
						LOGGER.finer("Test 3: Socket timeout while receiving the response.");
						timeSinceFirstTransmission += timeout;
						int timeoutAddValue = (timeSinceFirstTransmission * 2);
						if (timeoutAddValue > 1600) timeoutAddValue = 1600;
						timeout = timeoutAddValue;
					} else {
						LOGGER.finer("Test 3: Socket timeout while receiving the response. Maximum retry limit exceed. Give up.");
						di.setPortRestrictedCone();
						LOGGER.finer("Node is behind a port restricted NAT.");
						return;
					}
				}
			}
		}finally{
			if(sendSocket != null && !sendSocket.isClosed()){
				sendSocket.close();
			}
		}
	}

	public void interrupt(){
		synchronized (interruptSemaphore) {

			while(running){

				interrupted = true;

				try {
					interruptSemaphore.wait(200);
				} catch (InterruptedException e) {

				}
			}
		}

	}
}
